package com.lc.zpyh.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.OnHttpListener;
import com.lc.zpyh.R;
import com.lc.zpyh.bean.BusinessEntity;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.DeleteOrderByMerchantIdApi;
import com.lc.zpyh.http.request.PublicMsgBean;
import com.lc.zpyh.http.response.SelectMyCartBean;
import com.lc.zpyh.other.IntentKey;

import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.BtnUtils;
import com.lc.zpyh.util.SPUtil;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.ButterKnife;

public class ShoppingCartDialog extends Dialog implements View.OnClickListener {

    private Context context;
    private String merchantId;
    private TextView tv_clear;
    private TextView tv_add_gouwuche,tv_money,tv_num,tv_order;
    private RecyclerView rv_shop;
    List<SelectMyCartBean.ListBean.CartsBean> dataarrtBeanList ;
    private OnGoodsOrderListener onGoodsOrderListener;
    private BaseQuickAdapter<SelectMyCartBean.ListBean.CartsBean, BaseViewHolder> shopAdapter;

    List<String> orderList=new ArrayList<>();
    private int price;
    private int count;

    private List<BusinessEntity> listbrow = new ArrayList<>();
    public ShoppingCartDialog(Context context, String merchantId,List<SelectMyCartBean.ListBean.CartsBean> datalist) {
        super(context, R.style.dialog);
        this.context = context;
        this.merchantId = merchantId;
        this.dataarrtBeanList=datalist;


    }
    public void  setDataList(List<SelectMyCartBean.ListBean.CartsBean> datalist){
        this.dataarrtBeanList=datalist;
        Log.e("@@", "setDataList: "+datalist.size() );
        shopAdapter.notifyDataSetChanged();
        jisuanqian();
    }

    private void jisuanqian() {
     String totalNum="0";
    String totalPrice="0";
        for (int i = 0; i < dataarrtBeanList.size(); i++) {
            if (dataarrtBeanList.get(i).getSpzt() == 0) {
                totalNum = BigDecimalUtils.add(totalNum, dataarrtBeanList.get(i).getCount() + "", 0);
                totalPrice = BigDecimalUtils.add(totalPrice, BigDecimalUtils.mul(BigDecimalUtils.div(dataarrtBeanList.get(i).getPrice() + "", "100", 2), dataarrtBeanList.get(i).getCount() + "", 2), 2);
            }
        }
        tv_num.setText("已选" + totalNum + "件");
        tv_money.setText(  totalPrice);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置为居中
//        window.setWindowAnimations(R.style.bottom_menu_animation); // 添加动画效果
        setContentView(R.layout.dialog_shoppingcart);
        WindowManager windowManager = ((Activity) context).getWindowManager();
//        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setAttributes(lp);
        setCanceledOnTouchOutside(true);// 点击Dialog外部消失



        initView();


    }
    private void initView() {

        tv_num = findViewById(R.id.tv_num);

        tv_money = findViewById(R.id.tv_money);
        rv_shop = findViewById(R.id.rv_shop);
        tv_clear = findViewById(R.id.tv_clear);
        tv_order = findViewById(R.id.tv_order);
        tv_order.setOnClickListener(this);
        tv_clear.setOnClickListener(this);

        jisuanqian();
        shopAdapter = new BaseQuickAdapter<SelectMyCartBean.ListBean.CartsBean,
                BaseViewHolder>(R.layout.item_dialog_shoppingcart, dataarrtBeanList) {

            @Override
            protected void convert(BaseViewHolder holder, SelectMyCartBean.ListBean.CartsBean bean) {
                  if (bean.getSpzt()!=0){
                      holder.setGone(R.id.rl_top,true);
                  }
                holder.setText(R.id.goods, bean.getCommodityName());
                if (bean.getNameOne()==null&&bean.getNameTwo()==null&&bean.getFjpl()==null){
                    holder.setText(R.id.tv_yueshou,"暂无规格");
                }else {

                    if (bean.getFjpl()!=null&&bean.getFjpl().size()>0){
                        String specification = "";
                        for (int i = 0; i < bean.getFjpl().size(); i++) {
                                      if (bean.getFjpl().get(i).getTitle()!=null) {
                                          specification = specification + bean.getFjpl().get(i).getTitle() + "、";
                                      }
                        }
//                        规格一有没有数据
                        if (bean.getNameOne()!=null){
//                            有数据判断规格二有没有
                            if (bean.getNameTwo()==null){
                                holder.setText(R.id.tv_yueshou,bean.getNameOne()+","+specification);
                            }else {
                                holder.setText(R.id.tv_yueshou,bean.getNameOne()+","+bean.getNameTwo()+","+specification);
                            }

                        }else {
                            holder.setText(R.id.tv_yueshou,specification);
                        }
                    }else {
                        if (bean.getNameTwo()!=null){
                            holder.setText(R.id.tv_yueshou,bean.getNameOne()+","+bean.getNameTwo());
                        }else {
                            holder.setText(R.id.tv_yueshou,bean.getNameOne());
                        }

                    }

                }

                GlideApp.with(context)
                        .load(IntentKey.CAR_IMAGE+bean.getSpimg())
                         .into((ImageView) holder.getView(R.id.img_dianpu));

                holder.setText(R.id.tv_xianjia, "￥"+BigDecimalUtils.div(bean.getPrice()+"","100",2));
                holder.setText(R.id.tv_number, bean.getCount()+"");

                if (bean.getCount()==0){
                    holder.setVisible(R.id.fl_reduce,false);
                    holder.setVisible(R.id.tv_number,false);

                }else {
                    holder.setVisible(R.id.fl_reduce,true);
                    holder.setVisible(R.id.tv_number,true);
                }
              count=  bean.getCount();
//                 if (CourseUtils.isNotNullOrEmpty(bean.getSpecificationId())){
//                     price = bean.getSpjg();
//                 }else {
//                     price = bean.getGgzjg();
//                 }
                 holder.getView(R.id.fl_reduce).setOnClickListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View view) {
//                         businessDao.deleteHistorySearch(bean.getCartId()+"");
                         if (BtnUtils.isFastClick()) {
                         if (onGoodsOrderListener != null) {
                             onGoodsOrderListener.onAddShoppingCart(bean.getCommodityId() + "", "-1", bean.getSpecificationId() + "", bean.getPrice() + "", bean.getCondimentsId() + "", bean.getCartId() + "", (bean.getCount() - 1) + "");

                         }

                         }

//                         listbrow = businessDao.findAll();
//                         for (int i = 0; i < listbrow.size(); i++) {
//                             Log.e("TAG", "onCreate: " + listbrow.get(i).getCartId());
//                         }
                     }
                 });
                holder.getView(R.id.fl_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (BtnUtils.isFastClick()) {
//                            businessDao = new BusinessDao(context);
//                            businessDao.add(bean.getCommodityId() + "",bean.getCartId()+"", (bean.getCount() + 1) + "");

                            if (onGoodsOrderListener != null) {
                                onGoodsOrderListener.onAddShoppingCart(bean.getCommodityId() + "", 1 + "", bean.getSpecificationId() + "", bean.getPrice() + "", bean.getCondimentsId() + "", bean.getCartId() + "", (bean.getCount() + 1) + "");
                            }
                        }

//                        listbrow = businessDao.findAll();
//                        for (int i = 0; i < listbrow.size(); i++) {
//                            Log.e("TAG", "onCreate: " + listbrow.get(i).getCartId());
//                        }

                    }


                });
            }


        };
        rv_shop.setAdapter(shopAdapter);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_order:

                if (onGoodsOrderListener != null) {
                    onGoodsOrderListener.OrderCom(orderList);
                    dismiss();
                }
                break;
            case R.id.tv_clear:

                deleteOrderByMerchantId();
                dismiss();
                break;



            default:
                break;
        }
    }
    private void deleteOrderByMerchantId() {
        EasyHttp.post(new ApplicationLifecycle())
                .api(new DeleteOrderByMerchantIdApi().setUserId(SPUtil.get(context, IntentKey.USERID,"")).setMerchantId(merchantId)).request(new OnHttpListener<PublicMsgBean>() {

            @Override
            public void onSucceed(PublicMsgBean data) {
                if (data.getCode()==0){
                  dataarrtBeanList.clear();
                    if (onGoodsOrderListener != null) {
                        onGoodsOrderListener.onSubShoppingCart();


                    }
                }
            }
            @Override
            public void onFail(Exception e) {


            }
        });
    }
    public interface OnGoodsOrderListener {
        void onDismiss(String[] specification, String num, String shopPrice, String intPrice, String vipPrice, String integralPrice, String deductionIntegral);

        void onAddShoppingCart(String id,String count,String specificationId,String price,String condimentsId,String cardId,String cartcount);
        void onSubShoppingCart();
        void OrderCom(List<String> orderList);

    }

    public void setOnGoodsOrderListener(OnGoodsOrderListener onGoodsOrderListener) {
        this.onGoodsOrderListener = onGoodsOrderListener;
    }
}
